package cn.linshu.security.jwt.service.impl;

import cn.linshu.security.jwt.entity.SysResource;
import cn.linshu.security.jwt.entity.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * -*- coding: utf-8 -*-
 *
 * @Author linnin
 * @Name springboot3-labs-master
 * @Time 2025/2/3 23:48
 * @Note
 * @For
 * @Out Copyright© 2025 linnin
 */

/* coding: utf-8 */

public class SysUserDetails implements UserDetails {
    // 定义常量来表示启用状态
    private static final int ENABLED = 1;

    //用户
    private final SysUser sysUser;
    //拥有资源列表
    private final List<SysResource> resourceList;

    public SysUserDetails(SysUser sysUser, List<SysResource> resourceList) {
        this.sysUser = sysUser;
        this.resourceList = resourceList;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
//        //返回当前用户所拥有的资源
//        return resourceList.stream()
//                .map(resource -> new SimpleGrantedAuthority(resource.getId() + ":" + resource.getName()))
//                .collect(Collectors.toList());
        // 返回当前用户所拥有的资源
        Collection<GrantedAuthority> resourceAuthorities = resourceList.stream()
                .map(resource -> new SimpleGrantedAuthority(resource.getId() + ":" + resource.getName()))
                .collect(Collectors.toList());

        // 添加静态权限（例如角色）
        Collection<GrantedAuthority> staticAuthorities = Stream.of(
                new SimpleGrantedAuthority("TEST_ROLE")
        ).collect(Collectors.toList());

        //添加角色

        // 合并资源权限和静态权限
        return Stream.concat(resourceAuthorities.stream(), staticAuthorities.stream())
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return this.sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return this.sysUser.getUsername();
    }

    @Override
    public boolean isEnabled() {
        // 空指针检查并简化逻辑
        return Objects.nonNull(this.sysUser) && this.sysUser.getEnable() == ENABLED;
    }

    public Integer getUserId() {
        return this.sysUser.getId();
    }
}